#include "mainwindow.h"
#include <QDebug>       // For placeholder messages
#include <QInputDialog> // For simple input if needed
#include <QHeaderView>  // For QTableWidget header customization
#include <QTimer>       // For QTimer

#include "sfts_client_api.h"
#include "gui_bridge.h"
#include "client_wrapper.h"

// 全局主窗口实例 (改为 extern 声明)
extern MainWindow *g_mainWindowInstance;

MainWindow::MainWindow(const QString &username, QWidget *parent)
    : QMainWindow(parent), m_currentUser(username), m_clientWrapper(nullptr), m_currentRemotePath("."), m_transferDialog(nullptr)
{
    // 设置全局实例
    g_mainWindowInstance = this;

    setupUi();
    setupConnections();
    setWindowTitle(tr("安全文件传输系统 - 用户: %1").arg(m_currentUser));
    appendLogMessage(tr("成功登录。用户: %1").arg(m_currentUser));

    // --- 连接到GUI信号器 ---
    connect(GuiSignaler::instance(), &GuiSignaler::fileListUpdated, this, &MainWindow::updateFileList, Qt::QueuedConnection);
    connect(GuiSignaler::instance(), &GuiSignaler::logMessageReceived, this, &MainWindow::appendLogMessage, Qt::QueuedConnection);
    connect(GuiSignaler::instance(), &GuiSignaler::transferProgressUpdated, this, &MainWindow::updateTransferProgress, Qt::QueuedConnection);
    connect(GuiSignaler::instance(), &GuiSignaler::transferCompleted, this, &MainWindow::onTransferCompletedInternal, Qt::QueuedConnection);
    // -------------------------------------

    requestInitialFileList();
}

MainWindow::MainWindow(const QString &username, ClientWrapper *clientWrapper, QWidget *parent)
    : QMainWindow(parent), m_currentUser(username), m_clientWrapper(clientWrapper), m_currentRemotePath("."), m_transferDialog(nullptr)
{
    // 设置全局实例
    g_mainWindowInstance = this;

    setupUi();
    setupConnections();
    setWindowTitle(tr("安全文件传输系统 - 用户: %1").arg(m_currentUser));
    appendLogMessage(tr("成功登录。用户: %1").arg(m_currentUser));

    if (m_clientWrapper)
    {
        connect(m_clientWrapper, &ClientWrapper::fileListUpdated, this, &MainWindow::updateFileList, Qt::QueuedConnection);
        connect(m_clientWrapper, &ClientWrapper::logMessage, this, &MainWindow::appendLogMessage, Qt::QueuedConnection);
        connect(m_clientWrapper, &ClientWrapper::transferProgress, this, &MainWindow::updateTransferProgress, Qt::QueuedConnection);
        connect(m_clientWrapper, &ClientWrapper::transferCompleted, this, &MainWindow::onTransferCompletedInternal, Qt::QueuedConnection);
        connect(m_clientWrapper, &ClientWrapper::deleteFileResult, this, &MainWindow::onDeleteFileResult, Qt::QueuedConnection);
    }
    else
    {
        connect(GuiSignaler::instance(), &GuiSignaler::fileListUpdated, this, &MainWindow::updateFileList, Qt::QueuedConnection);
        connect(GuiSignaler::instance(), &GuiSignaler::logMessageReceived, this, &MainWindow::appendLogMessage, Qt::QueuedConnection);
        connect(GuiSignaler::instance(), &GuiSignaler::transferProgressUpdated, this, &MainWindow::updateTransferProgress, Qt::QueuedConnection);
        connect(GuiSignaler::instance(), &GuiSignaler::transferCompleted, this, &MainWindow::onTransferCompletedInternal, Qt::QueuedConnection);
    }
    requestInitialFileList();
}

MainWindow::~MainWindow()
{
    delete m_transferDialog;
}

void MainWindow::setupUi()
{
    QWidget *centralWidget = new QWidget(this);
    setCentralWidget(centralWidget);

    QVBoxLayout *mainLayout = new QVBoxLayout(centralWidget);
    QSplitter *splitter = new QSplitter(Qt::Horizontal, this);

    // --- File Operations Area ---
    m_fileOpsGroupBox = new QGroupBox(tr("文件操作区"));
    QVBoxLayout *fileOpsLayout = new QVBoxLayout;

    m_fileTableWidget = new QTableWidget;
    m_fileTableWidget->setColumnCount(4);
    QStringList headers = {tr("名称"), tr("类型"), tr("大小"), tr("修改日期")};
    m_fileTableWidget->setHorizontalHeaderLabels(headers);
    m_fileTableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
    m_fileTableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
    m_fileTableWidget->verticalHeader()->setVisible(false);
    m_fileTableWidget->horizontalHeader()->setStretchLastSection(true);

    m_uploadButton = new QPushButton(tr("上传文件"));
    m_downloadButton = new QPushButton(tr("下载文件"));
    m_deleteButton = new QPushButton(tr("删除文件"));
    m_refreshFileListButton = new QPushButton(tr("刷新列表"));
    m_logoutButton = new QPushButton(tr("退出登录"));

    QHBoxLayout *fileButtonLayout = new QHBoxLayout;
    fileButtonLayout->addWidget(m_uploadButton);
    fileButtonLayout->addWidget(m_downloadButton);
    fileButtonLayout->addWidget(m_deleteButton);
    fileButtonLayout->addWidget(m_refreshFileListButton);
    fileButtonLayout->addStretch();
    fileButtonLayout->addWidget(m_logoutButton);

    fileOpsLayout->addWidget(new QLabel(tr("服务器文件列表 (%1):").arg(m_currentRemotePath)), 0, Qt::AlignLeft);
    fileOpsLayout->addWidget(m_fileTableWidget, 1);
    fileOpsLayout->addLayout(fileButtonLayout);
    m_fileOpsGroupBox->setLayout(fileOpsLayout);

    // --- Log Viewing Area ---
    m_logViewGroupBox = new QGroupBox(tr("操作日志区"));
    QVBoxLayout *logViewLayout = new QVBoxLayout;
    m_logTextEdit = new QTextEdit;
    m_logTextEdit->setReadOnly(true);
    logViewLayout->addWidget(m_logTextEdit);
    m_logViewGroupBox->setLayout(logViewLayout);

    splitter->addWidget(m_fileOpsGroupBox);
    splitter->addWidget(m_logViewGroupBox);
    splitter->setStretchFactor(0, 2);
    splitter->setStretchFactor(1, 1);

    mainLayout->addWidget(splitter);
    centralWidget->setLayout(mainLayout);

    resize(800, 600);
}

void MainWindow::setupConnections()
{
    connect(m_uploadButton, &QPushButton::clicked, this, &MainWindow::onUploadButtonClicked);
    connect(m_downloadButton, &QPushButton::clicked, this, &MainWindow::onDownloadButtonClicked);
    connect(m_deleteButton, &QPushButton::clicked, this, &MainWindow::onDeleteButtonClicked);
    connect(m_refreshFileListButton, &QPushButton::clicked, this, &MainWindow::onRefreshFileListClicked);
    connect(m_logoutButton, &QPushButton::clicked, this, &MainWindow::onLogoutButtonClicked);
    connect(m_fileTableWidget, &QTableWidget::itemDoubleClicked, this, &MainWindow::onFileTableItemDoubleClicked);
}

void MainWindow::requestInitialFileList()
{
    appendLogMessage(tr("正在获取根目录文件列表..."));
    if (m_clientWrapper)
    {
        m_clientWrapper->requestFileList(m_currentRemotePath);
    }
    else
    {
        int ret = sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
        if (ret != 0)
            appendLogMessage(tr("请求文件列表失败 (错误码: %1)").arg(ret), true);
    }
}

void MainWindow::onUploadButtonClicked()
{
    QString localFilePath = QFileDialog::getOpenFileName(this, tr("选择要上传的文件"));
    if (localFilePath.isEmpty())
        return;

    QFileInfo fileInfo(localFilePath);
    QString fileName = fileInfo.fileName();
    QString remotePath = m_currentRemotePath == "." ? fileName : m_currentRemotePath + "/" + fileName;

    appendLogMessage(tr("准备上传文件: %1 作为 %2").arg(localFilePath).arg(remotePath));

    if (m_transferDialog)
    {
        delete m_transferDialog;
        m_transferDialog = nullptr;
    }
    m_transferDialog = new TransferProgressDialog(tr("上传: %1").arg(fileName), fileName, this);
    if (m_clientWrapper)
    {
        connect(m_transferDialog, &TransferProgressDialog::cancelRequested,
                m_clientWrapper, &ClientWrapper::cancelTransfer, Qt::UniqueConnection);
    }
    m_transferDialog->show();

    if (m_clientWrapper)
        m_clientWrapper->uploadFile(localFilePath, remotePath);
    else
    {
        m_transferDialog->markError(tr("直接C API调用不支持详细进度。"));
    }
}

void MainWindow::onDownloadButtonClicked()
{
    QList<QTableWidgetItem *> selectedItems = m_fileTableWidget->selectedItems();
    if (selectedItems.isEmpty())
    {
        QMessageBox::warning(this, tr("下载错误"), tr("请先选择一个文件进行下载。"));
        return;
    }

    QTableWidgetItem *nameItem = m_fileTableWidget->item(m_fileTableWidget->currentRow(), 0);
    if (!nameItem)
        return;

    FileItem selectedFile = nameItem->data(Qt::UserRole).value<FileItem>();
    QString remoteFileName = selectedFile.name;
    QString fullRemotePath = m_currentRemotePath == "." ? remoteFileName : m_currentRemotePath + "/" + remoteFileName;

    if (selectedFile.type == QLatin1String("directory"))
    {
        QMessageBox::information(this, tr("下载"), tr("不能直接下载目录: %1").arg(remoteFileName));
        return;
    }

    QString localSavePath = QFileDialog::getSaveFileName(this, tr("选择保存路径"), remoteFileName);
    if (localSavePath.isEmpty())
        return;

    appendLogMessage(tr("准备下载文件: %1 到 %2").arg(fullRemotePath).arg(localSavePath));

    if (m_transferDialog)
    {
        delete m_transferDialog;
        m_transferDialog = nullptr;
    }
    m_transferDialog = new TransferProgressDialog(tr("下载: %1").arg(remoteFileName), remoteFileName, this);
    if (m_clientWrapper)
    {
        connect(m_transferDialog, &TransferProgressDialog::cancelRequested,
                m_clientWrapper, &ClientWrapper::cancelTransfer, Qt::UniqueConnection);
    }
    m_transferDialog->show();

    if (m_clientWrapper)
        m_clientWrapper->downloadFile(fullRemotePath, localSavePath);
    else
    {
        m_transferDialog->markError(tr("直接C API调用不支持详细进度。"));
    }
}

void MainWindow::onRefreshFileListClicked()
{
    appendLogMessage(tr("正在刷新目录 %1 的文件列表...").arg(m_currentRemotePath));
    if (m_clientWrapper)
        m_clientWrapper->requestFileList(m_currentRemotePath);
    else
    {
        int ret = sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
        if (ret != 0)
            appendLogMessage(tr("刷新文件列表请求失败 (错误码: %1)").arg(ret), true);
    }
}

void MainWindow::onLogoutButtonClicked()
{
    appendLogMessage(tr("正在退出登录..."));
    bool logout_initiated = false;
    if (m_clientWrapper)
    {
        logout_initiated = m_clientWrapper->logout();
    }
    else
    {
        int ret = sfts_client_logout();
        logout_initiated = (ret == 0);
    }

    if (logout_initiated)
    {
        appendLogMessage(tr("注销请求已发送。"));
        emit loggedOut(); // Emit the signal
    }
    else
    {
        appendLogMessage(tr("注销请求未能发送。"), true);
        // Optionally, still emit loggedOut if we want to close the window regardless
        // emit loggedOut();
    }
    close(); // Close the main window
}

void MainWindow::onFileTableItemDoubleClicked(QTableWidgetItem *item)
{
    if (!item)
        return;

    QTableWidgetItem *nameItem = m_fileTableWidget->item(item->row(), 0);
    if (!nameItem)
        return;

    FileItem fileData = nameItem->data(Qt::UserRole).value<FileItem>();

    if (fileData.type == QLatin1String("directory"))
    {
        appendLogMessage(tr("尝试进入目录: %1").arg(fileData.name));
        if (fileData.name == "..")
        {
            if (m_currentRemotePath == "." || m_currentRemotePath == "/")
            {
                // Already at root or relative root, can't go up further with ".." alone
                // Or decide to refresh current if that's the desired behavior for ".." at root
            }
            else
            {
                int lastSlash = m_currentRemotePath.lastIndexOf('/');
                if (lastSlash > 0)
                {
                    m_currentRemotePath = m_currentRemotePath.left(lastSlash);
                }
                else
                { // Was a top-level directory like "somedir", now go to root "."
                    m_currentRemotePath = ".";
                }
            }
        }
        else if (fileData.name == ".")
        { // Refresh current directory
          // No change to m_currentRemotePath
        }
        else
        { // Go into subdirectory
            if (m_currentRemotePath == "." || m_currentRemotePath == "/")
            {
                m_currentRemotePath = fileData.name;
            }
            else
            {
                m_currentRemotePath += "/" + fileData.name;
            }
        }

        onRefreshFileListClicked(); // Refresh list for the new path
    }
    else
    {
        appendLogMessage(tr("双击文件: %1 (类型: %2)").arg(fileData.name).arg(fileData.type));
        m_fileTableWidget->setCurrentItem(item);
        onDownloadButtonClicked();
    }
}

void MainWindow::onDeleteButtonClicked()
{
    QList<QTableWidgetItem *> selectedItems = m_fileTableWidget->selectedItems();
    if (selectedItems.isEmpty())
    {
        QMessageBox::warning(this, tr("删除错误"), tr("请先选择一个文件或目录进行删除。"));
        return;
    }

    QTableWidgetItem *nameItem = m_fileTableWidget->item(m_fileTableWidget->currentRow(), 0);
    if (!nameItem)
        return;

    FileItem selectedFile = nameItem->data(Qt::UserRole).value<FileItem>();
    QString remoteFileName = selectedFile.name;
    QString fullRemotePath = m_currentRemotePath == "." ? remoteFileName : m_currentRemotePath + "/" + remoteFileName;

    QMessageBox::StandardButton reply;
    reply = QMessageBox::question(this, tr("确认删除"), tr("确定要删除服务器上的 '%1' 吗？\n类型: %2").arg(fullRemotePath).arg(selectedFile.type),
                                  QMessageBox::Yes | QMessageBox::No);
    if (reply == QMessageBox::Yes)
    {
        appendLogMessage(tr("准备删除: %1").arg(fullRemotePath));
        m_deleteButton->setEnabled(false); // Disable button during operation

        if (m_clientWrapper)
        {
            m_clientWrapper->deleteFile(fullRemotePath);
            // Result will be handled by onDeleteFileResult slot
        }
        else
        {
            // Direct C API call - no direct callback for success/failure here
            int ret = sfts_client_delete_file(fullRemotePath.toStdString().c_str());
            if (ret != 0)
            {
                appendLogMessage(tr("删除 '%1' 的请求发送失败 (错误码: %2)").arg(fullRemotePath).arg(ret), true);
                m_deleteButton->setEnabled(true);
            }
            else
            {
                appendLogMessage(tr("删除 '%1' 的请求已发送。请手动刷新列表以查看结果。").arg(fullRemotePath));
                // We don't get a direct confirmation, so re-enable and suggest refresh.
                // Optionally, could do an optimistic refresh after a short delay.
                m_deleteButton->setEnabled(true);
            }
        }
    }
    else
    {
        appendLogMessage(tr("取消删除操作: %1").arg(fullRemotePath));
    }
}

void MainWindow::onDeleteFileResult(bool success, const QString &filename, const QString &message)
{
    m_deleteButton->setEnabled(true); // Re-enable button
    if (success)
    {
        appendLogMessage(tr("成功删除 '%1': %2").arg(filename).arg(message));
        onRefreshFileListClicked(); // Refresh the file list
    }
    else
    {
        appendLogMessage(tr("删除 '%1' 失败: %2").arg(filename).arg(message), true);
        QMessageBox::critical(this, tr("删除失败"), tr("无法删除文件 '%1'。\n原因: %2").arg(filename).arg(message));
    }
}

void MainWindow::updateFileList(const QList<FileItem> &files)
{
    // 添加文件列表获取成功的消息
    appendLogMessage(tr("获取目录 %1 的文件列表成功，共 %2 个项目").arg(m_currentRemotePath).arg(files.count()));

    populateFileList(files);
    QLabel *pathLabel = m_fileOpsGroupBox->layout()->itemAt(0)->widget()->findChild<QLabel *>();
    if (pathLabel)
    {
        pathLabel->setText(tr("服务器文件列表 (%1):").arg(m_currentRemotePath));
    }
}

void MainWindow::populateFileList(const QList<FileItem> &files)
{
    m_fileTableWidget->setRowCount(0);
    m_fileTableWidget->setRowCount(files.count());

    for (int i = 0; i < files.count(); ++i)
    {
        const FileItem &file = files.at(i);
        QTableWidgetItem *nameItem = new QTableWidgetItem(file.name);
        QTableWidgetItem *typeItem = new QTableWidgetItem(file.type);
        QTableWidgetItem *sizeItem = new QTableWidgetItem(file.type == QLatin1String("directory") ? tr("-") : QString::number(file.size));
        QTableWidgetItem *modItem = new QTableWidgetItem(file.lastModified);

        nameItem->setData(Qt::UserRole, QVariant::fromValue(file));

        if (file.type == QLatin1String("directory"))
        {
            nameItem->setIcon(QApplication::style()->standardIcon(QStyle::SP_DirIcon));
        }
        else
        {
            nameItem->setIcon(QApplication::style()->standardIcon(QStyle::SP_FileIcon));
        }

        m_fileTableWidget->setItem(i, 0, nameItem);
        m_fileTableWidget->setItem(i, 1, typeItem);
        m_fileTableWidget->setItem(i, 2, sizeItem);
        m_fileTableWidget->setItem(i, 3, modItem);
    }
    m_fileTableWidget->resizeColumnsToContents();
    m_fileTableWidget->horizontalHeader()->setStretchLastSection(true);
}

void MainWindow::appendLogMessage(const QString &message, bool isError)
{
    QTime currentTime = QTime::currentTime();
    QString formattedMessage = currentTime.toString("hh:mm:ss") + " - " + message;
    if (isError)
    {
        m_logTextEdit->append(QString("<font color='red'>%1</font>").arg(formattedMessage));
    }
    else
    {
        m_logTextEdit->append(formattedMessage);
    }
}

void MainWindow::updateTransferProgress(const QString &fileName, int percentage, const QString &status)
{
    QString progressMsg = tr("传输 %1: %2% - %3").arg(fileName).arg(percentage).arg(status);
    appendLogMessage(progressMsg);

    if (m_transferDialog && m_transferDialog->isVisible())
    {
        m_transferDialog->updateProgress(percentage, status);
    }
}

void MainWindow::onTransferCompletedInternal(const QString &filename, bool success, const QString &message)
{
    if (success)
    {
        appendLogMessage(tr("文件 '%1' 传输成功: %2").arg(filename).arg(message));

        // 增加延迟时间到4秒，给服务器更多恢复时间
        QTimer::singleShot(4000, this, [this, filename]()
                           {
            appendLogMessage(tr("正在刷新文件列表..."));
            
            // 使用直接请求方式而非手动实现的重试机制，让底层自动恢复机制处理
            if (m_clientWrapper)
            {
                m_clientWrapper->requestFileList(m_currentRemotePath);
            }
            else
            {
                int ret = sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
                if (ret != 0) {
                    // 如果失败，静默再次尝试
                    QTimer::singleShot(2000, this, [this]() {
                        sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
                    });
                }
            } });

        if (m_transferDialog && m_transferDialog->isVisible())
        {
            m_transferDialog->markCompleted(tr("成功: %1").arg(message));
        }
    }
    else
    {
        appendLogMessage(tr("文件 '%1' 传输失败: %2").arg(filename).arg(message), true);
        if (m_transferDialog && m_transferDialog->isVisible())
        {
            m_transferDialog->markError(tr("失败: %1").arg(message));
        }
    }
}

void MainWindow::handleUploadSuccess(const QString &fileName)
{
    appendLogMessage(tr("上传 '%1' 成功完成。").arg(fileName));
    // 添加与下载相同的延迟刷新逻辑
    QTimer::singleShot(4000, this, [this, fileName]()
                       {
        appendLogMessage(tr("正在刷新文件列表..."));
        
        // 使用直接请求方式而非手动实现的重试机制，让底层自动恢复机制处理
        if (m_clientWrapper)
        {
            m_clientWrapper->requestFileList(m_currentRemotePath);
        }
        else
        {
            int ret = sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
            if (ret != 0) {
                // 如果失败，静默再次尝试
                QTimer::singleShot(2000, this, [this]() {
                    sfts_client_request_file_list(m_currentRemotePath.toStdString().c_str());
                });
            }
        } });
}

void MainWindow::handleUploadFailure(const QString &fileName, const QString &errorMsg)
{
    appendLogMessage(tr("上传 '%1' 失败: %2").arg(fileName).arg(errorMsg), true);
}

void MainWindow::handleDownloadSuccess(const QString &fileName)
{
    appendLogMessage(tr("下载 '%1' 成功完成。").arg(fileName));
}

void MainWindow::handleDownloadFailure(const QString &fileName, const QString &errorMsg)
{
    appendLogMessage(tr("下载 '%1' 失败: %2").arg(fileName).arg(errorMsg), true);
}